package com.atguigu.juc_day02;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * java
 * 2022/9/8 20 06
 */
class AirCondition1{
    private int number = 0;
    private Lock lock = new ReentrantLock(true);
    private Condition condition = lock.newCondition ();

    public void increment() throws InterruptedException {
        lock.lock ();
        try {
            while (number!=0){
                condition.await ();
            }
            number++;
            System.out.println (Thread.currentThread ().getName ()+"添加了1，目前为"+number);
            condition.signalAll ();
        }finally {
            lock.unlock ();
        }
    }
    public void decrement() throws InterruptedException {
        lock.lock ();
        while (number==0){
            condition.await ();
        }
        number--;
        System.out.println (Thread.currentThread ().getName ()+"减少了1，目前为"+number);
        condition.signalAll ();
        lock.unlock ();
    }
}
public class ProdConsumerDemo1 {
    public static void main (String[] args) {
        AirCondition1 airCondition1 = new AirCondition1 ();
        new Thread (()->{
            for (int i = 0; i < 10; i++) {
                try {
                    airCondition1.increment ();
                } catch (InterruptedException e) {
                    throw new RuntimeException (e);
                }
            }
        },"A").start ();
        new Thread (()->{
            for (int i = 0; i < 10; i++) {
                try {
                    airCondition1.decrement ();
                } catch (InterruptedException e) {
                    throw new RuntimeException (e);
                }
            }
        },"B").start ();
        new Thread (()->{
            for (int i = 0; i < 10; i++) {
                try {
                    airCondition1.increment ();
                } catch (InterruptedException e) {
                    throw new RuntimeException (e);
                }
            }
        },"C").start ();
        new Thread (()->{
            for (int i = 0; i < 10; i++) {
                try {
                    airCondition1.decrement ();
                } catch (InterruptedException e) {
                    throw new RuntimeException (e);
                }
            }
        },"D").start ();
    }
}
